-- Wreckage
-- Created by chengb Feb/3/2016
-- 残骸格子

-- 初始化
function initWreckage(self)
    local class = self.gridData.class;
    local buildingInfo = BuildingBonusM.queryBuildingView(class);

    if not buildingInfo then
        error("获取不到建筑查看配置，元素类型：" .. class);
        return;
    end

    -- 建筑图标
    local iconPath = getLevelItemIconPath(buildingInfo["icon"]);

    self.icon = ccui.ImageView:create(iconPath);
    self.icon:setTouchEnabled(true);
    self.item:addChild(self.icon);
    self.iconPath = iconPath;

    -- 查看残骸
    local function viewWreckage()
        -- 需要替换图片
        if buildingInfo["icon2"] and buildingInfo["icon2"] ~= "" then
            local changeIconPath = getLevelItemIconPath(buildingInfo["icon2"]);
            self.icon:loadTexture(changeIconPath);
        end

        -- 领取残骸奖励
        if DungeonInstanceM.isInInstance() then
            -- 如果在副本中，走副本奖励流程
            DungeonActionM.go("take_instance_bonus", self.gridData:getPos());
        else
            -- 不在副本中，走通用奖励流程
            DungeonActionM.go("take_wreckage_bonus", self.gridData:getPos());
        end

        EventMgr.fire(event.PLAYER_MOVE, self.gridData:getPos());
    end

    local function onClicked(sender, eventType)
        if eventType == ccui.TouchEventType.began then
            if self.gridData.state == GRID_STATE_DISABLE then
                -- 已经失效，不处理
                return;
            end

            -- boss层中
            local dungeonId = DungeonM.getDungeonId();
            local layer     = DungeonM.currentLayer();
            if DungeonBossM.isBossLayer(dungeonId, layer) and not DungeonM.isAllMonsterDead() then
                alert(getLocStr("pick_up_instance_target_fail"));
                return;
            end

            -- 更新建筑访问
            self:updateBuildingVisit();

            -- 音效
            AudioM.playFx("button_spell");

            if (DungeonInstanceM.isInInstance() or self.gridData.monster_die_limit == 1) and
                not DungeonM.isAllMonsterDead() then
                -- 如果在副本中，需要击杀所有怪物方可拾取
                self:openBuildingView(nil, -20, buildingInfo["dialog2"], getLocStr("btn_text_leave"));
                return;
            end

            -- 打开建筑查看界面
            self:openBuildingView(viewWreckage);
        end
    end
    self.icon:addTouchEventListener(onClicked);
end

-- 领取冒险者残骸奖励的事件回调
function onTakeWreckage(self, bonusList)
    -- 播放建筑奖励特效
    buildingBonusEffect(self);

    if bonusList then
        self:playBonusListEffect(bonusList);
    else
        self.item:removeAllChildren();
    end

    self:showBuildingBonusTip();
end
